package com.my.micro.service.order.decode;

import com.my.micro.service.order.result.BaseResult;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 自定义Feign解码
 * 解析Feign接口返回的BaseResult, 校验并返回实际结果
 *
 * @author Zijian Liao
 * @since 1.0.0
 */
public class BaseResultDecode extends ResponseEntityDecoder {

    public BaseResultDecode(Decoder decoder) {
        super(decoder);
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        // type是个纯粹的object 或者 type是个带有泛型的Object但返回的类型不是BaseResult
        if (!(type instanceof ParameterizedTypeImpl)
                || ((ParameterizedTypeImpl) type).getRawType() != BaseResult.class) {

            // 将Feign接口中返回的类型封装到BaseResult中
            // 比如Feign接口的类型为 Goods, 经过这行代码就会得到 BaseResult<Goods>
            type = ParameterizedTypeImpl.make(BaseResult.class, new Type[]{type}, null);
            // 将BaseResult<Goods>交由父类进行解析
            Object object = super.decode(response, type);
            BaseResult<?> result = (BaseResult<?>) object;
            return result.getData();
        }
        return super.decode(response, type);
    }
}
